import datetime
from pathlib import Path

import fitz  # pymupdf
import numpy as np
import pandas as pd
import tabula
import win32com.client
from docx import Document
from loguru import logger

from utils.tools import get_md5


def save_file(io_bytes, url):
    url_path = Path(url)
    file_name = get_md5(url)
    file_path = (
        f"/tmp/tax_honor/{datetime.datetime.now().strftime('%Y-%m-%d')}_{file_name}.{url_path.name.split('.')[-1]}"
    )
    tmp_path = Path(file_path)
    tmp_path.parent.mkdir(exist_ok=True)
    if not tmp_path.exists():
        tmp_path.write_bytes(io_bytes)
        logger.info(f"保存文件 {file_path}")
    return file_path


def read_tables_from_docx(file_path):

    output_path = file_path

    if Path(file_path).suffix == ".doc":
        output_path = file_path.replace(".doc", ".docx")
        convert_doc_to_docx(input_path=file_path, output_path=output_path)

    doc = Document(output_path)
    tables_df = []

    title = []

    for table in doc.tables:
        table_data = []
        for idx, row in enumerate(table.rows):
            if idx == 0:
                title = [cell.text for cell in row.cells]
                continue
            row_data = [cell.text for cell in row.cells]
            table_data.append(row_data)
        df = pd.DataFrame(table_data, columns=title)
        df = df.astype(str)
        tables_df.append(df)

    return tables_df


def extract_links_from_docx(file_path):
    links = []
    output_path = file_path
    if Path(file_path).suffix == ".doc":
        output_path = file_path.replace(".doc", ".docx")
        convert_doc_to_docx(input_path=file_path, output_path=output_path)

    doc = Document(output_path)
    for paragraph in doc.paragraphs:
        # 遍历段落中的每个超链接
        for run in paragraph.runs:
            if "HYPERLINK" in run.text:
                # 提取链接部分的文本（可以进一步解析具体的格式）
                links.append(run.text)
    return links


def convert_doc_to_docx(input_path, output_path):
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = False  # 隐藏 Word 窗口
    try:
        doc = word.Documents.Open(input_path)
        doc.SaveAs(output_path, FileFormat=16)  # 16 表示保存为 .docx 格式
    except Exception as e:
        print(f"doc 转 docx 转换失败: {e}")
    finally:
        doc.Close()
        word.Quit()


def extract_links_from_pdf(file_path):
    links = []
    pdf = fitz.open(file_path)
    for page_num in range(len(pdf)):
        page = pdf[page_num]
        for link in page.get_links():
            if link.get("uri"):  # 获取链接地址
                links.append((page_num + 1, link["uri"]))
    return links


def extract_tables_from_pdf(file_path):
    tables = tabula.read_pdf(file_path, pages="all")
    res = []
    for table in tables:
        table.replace({np.nan: ""}, inplace=True)
        table = table.astype(str)
        res.append(table)
    return res


if __name__ == "__main__":
    datas = extract_tables_from_pdf(r"C:\Users\wk\Downloads\eafbdf43685f40d494b02d9fe3bff6ed.pdf")
    for i in datas:
        for j in i.iterrows():
            idx, row = j
            print(row.to_list())
        print("-" * 100)
